package com.jr.bitcoin.Rpc;

import com.alibaba.fastjson.JSONObject;
import com.jr.bitcoin.Constants;
import com.jr.bitcoin.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:raojianfei
 * @email:
 * @desc: 该类用于实现通过 rpc 访问调用 bitcoin core 的 getbestblockhash 功能
 * @datetime: 2021/12/26 10:57
 */
public class GettBestBlockHash {
    public static String getBestBlockHash(){
        //准备rpc 请求的用户身份信息，及对一的Base64 格式
        String author = Constants.BITCOIN_RPC_USER+":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());


        //请求头的属性设置
        Map<String,String> header = new HashMap<>();
        header.put("ContentType" , "application/json");
        header.put("Authorization","Basic " +authorBase64);

        //准备rpc 请求的数据
        Map<String,Object> body = new HashMap<>();
        body.put("id",1314);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");
        byte[] bodyBytes = JSONObject.toJSONBytes(body);


        //{"id": 1314, "result":"xxx","error": null}
        String result = HttpUtils.post(
                Constants.BITCOIN_RPC_URL,
                header,
                bodyBytes
        );

        //反序列化，得到 result 的值

        return result;
    }
}
